﻿using System.Windows.Forms;
using System;
using System.Drawing;

namespace CGM
{
	public abstract class DataItem
	{
		/////////////////////////////////////////////////////////////////////////////
		// public events

		public event EventHandler NameChanged;

		/////////////////////////////////////////////////////////////////////////////
		// public properties

		public string Title
		{
			get { return m_Filename.NameExtension + (m_bDirty ? "*" : ""); }
		}

		public bool HasFilename
		{
			get { return m_Filename.Path != null && m_Filename.Path != ""; }
		}

		public string FileFilter
		{
			get { return m_strFileFilter; }
		}

		/////////////////////////////////////////////////////////////////////////////
		// protected properties

		protected bool Dirty
		{
			set
			{
				m_bDirty = value;
				if (NameChanged != null) NameChanged.Invoke(this, new EventArgs());
			}
		}

		/////////////////////////////////////////////////////////////////////////////
		// public methods

		public DataItem(string _strDescription, string _strExtension)
		{
			// set up data
			m_Filename = new Filename("Untitled." + _strExtension);
			m_bDirty = true;
			m_strFileFilter = _strDescription + " (*." + _strExtension + ")|*." + _strExtension;

			// the name has changed
			if (NameChanged != null) NameChanged.Invoke(this, new EventArgs());
		}

		public bool Save()
		{
			// call the derived save function
			if (SaveFile(m_Filename.PathNameExtension))
			{
				m_bDirty = false;
				if (NameChanged != null) NameChanged.Invoke(this, new EventArgs());
				return true;
			}

			return false;
		}

		public bool SaveAs(string _strFilename)
		{
			// call the derived save function
			if (SaveFile(_strFilename))
			{
				// save the filename
				m_Filename.PathNameExtension = _strFilename;
				m_bDirty = false;
				if (NameChanged != null) NameChanged.Invoke(this, new EventArgs());
				return true;
			}

			return true;
		}

		public bool Open(string _strFilename)
		{
			// call the derived open function
			if (OpenFile(_strFilename))
			{
				m_Filename.PathNameExtension = _strFilename;
				m_bDirty = false;
				if (NameChanged != null) NameChanged.Invoke(this, new EventArgs());
				return true;
			}

			return false;
		}

		/////////////////////////////////////////////////////////////////////////////
		// protected abstract methods

		protected abstract bool SaveFile(string _strFilename);
		protected abstract bool OpenFile(string _strFilename);

		/////////////////////////////////////////////////////////////////////////////
		// private fields

		// file information
		private Filename m_Filename;
		private bool m_bDirty;
		private string m_strFileFilter;
	}
}
